import win32gui
import win32con
import win32process
import win32api
import logging
import time
import sys

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    handlers=[
        logging.StreamHandler(sys.stdout)
    ]
)

def find_cursor_window():
    """查找Cursor窗口句柄"""
    def callback(hwnd, windows):
        if win32gui.IsWindowVisible(hwnd):
            title = win32gui.GetWindowText(hwnd)
            # 更精确地匹配Cursor IDE窗口
            if ("Cursor" in title and 
                "Eclipse" not in title and 
                not any(title.endswith(ext) for ext in [".java", ".py", ".xml", ".txt", ".md"])):
                windows.append((hwnd, title))
        return True
    
    windows = []
    win32gui.EnumWindows(callback, windows)
    if windows:
        hwnd, title = windows[0]
        logging.info(f"找到Cursor窗口: {title} (句柄: {hwnd})")
        return hwnd
    logging.error("未找到Cursor窗口")
    return None

def activate_cursor_window():
    """激活Cursor窗口"""
    hwnd = find_cursor_window()
    if not hwnd:
        return False
        
    try:
        # 获取当前线程ID
        current_thread = win32api.GetCurrentThreadId()
        # 获取目标窗口线程ID
        target_thread = win32process.GetWindowThreadProcessId(hwnd)[0]
        
        # 检查窗口是否有效
        if not win32gui.IsWindow(hwnd):
            logging.error("目标窗口无效")
            return False
            
        # 检查窗口是否可见
        if not win32gui.IsWindowVisible(hwnd):
            logging.error("目标窗口不可见")
            return False
        
        # 附加线程输入
        win32process.AttachThreadInput(current_thread, target_thread, True)
        
        try:
            # 确保窗口可见
            if win32gui.IsIconic(hwnd):
                win32gui.ShowWindow(hwnd, win32con.SW_RESTORE)
            
            # 将窗口带到前台
            win32gui.BringWindowToTop(hwnd)
            
            # 尝试激活窗口，最多重试3次
            for attempt in range(3):
                try:
                    win32gui.SetForegroundWindow(hwnd)
                    # 等待一小段时间确保窗口真正激活
                    time.sleep(0.1)
                    if win32gui.GetForegroundWindow() == hwnd:
                        logging.info("Cursor窗口已成功激活")
                        return True
                except Exception as e:
                    logging.warning(f"第{attempt + 1}次尝试激活窗口失败: {str(e)}")
                    time.sleep(0.2)  # 在重试之前等待
            
            logging.error("多次尝试后仍无法激活Cursor窗口")
            return False
            
        finally:
            # 确保分离线程输入
            try:
                win32process.AttachThreadInput(current_thread, target_thread, False)
            except Exception as e:
                logging.warning(f"分离线程输入时出错: {str(e)}")
        
    except Exception as e:
        logging.error(f"激活Cursor窗口时出错: {str(e)}")
        return False

if __name__ == "__main__":
    activate_cursor_window() 